﻿using MyBasicLib.Collections.Generic;
using MyBasicLib.Data.ORMLiteNew;
using MyBasicLib.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using MyBasicLib.Linq.Expressions;
using MyBasicLib.Extensions;
namespace MyBasicLib.Data.ORMLiteV2
{
    public class TableNameAliasCache
    {
        private readonly ICache<string, string> cacheName = new SimpleCache<string, string>();
        public static  readonly IMappingProvider MappingProvider = IOC.DefaultContainer.Resolve<IMappingProvider>();
        /// <summary>
        /// 
        /// </summary>
        /// <param name="exp"></param> 
        /// <remarks>
        /// p=>p.p
        /// p=>p.Id
        /// p=>p.t.Id
        /// p.Id
        /// p.t.Id
        /// p.t
        /// </remarks>
        /// <returns> 
        /// </returns>
        public string GetTableAlias(Expression exp)
        {
            Check.Argument.IsNotNull(exp, "exp");
            var key = GetTableAliasKey(exp);
            return cacheName.FetchOrCreateItem(key, p => "t" + cacheName.Count);
        }

        private static string GetTableAliasKey(Expression exp)
        {
            Expression nExp = exp.TrimUnary();   //简化
            var lExp = nExp as LambdaExpression; //
            if (lExp != null)                   //
                nExp = lExp.Body.TrimUnary();               //

            var key = string.Empty;
            var pe = nExp as ParameterExpression; //p
            if (pe != null)                       //
            {                                     //
                key = pe.Name;                    //
                return key;                       //
            }                                     //

            MemberExpression mp = nExp as MemberExpression;//出错
            if (mp == null)                               //
                return key;                               // 
            if (MappingProvider.IsValidTableClass(mp.Type))
            {
                return mp.Member.Name;
            }
            return GetTableAliasKey(mp.Expression);//p.t...   

        }
    }
}
